<template>
  <div>
    <!-- :footerBtnList="footerBtnList" -->
    <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" 
      :btnListTable="btnListTable" :isFixedColumn="true" :columnWidth="220" :isMore="false" :tableLoading="loading"
      :total="total" @pageSize="handlePageSize" @currentPage="handleCurrentPage">
      <!-- 条件组,插槽 -->
      <template #default>
        <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
          <el-form-item label="用户状态">
            <el-select v-model="formBtnList.status" placeholder="状态" style="width: 90px" @change="handleOnSelect">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="formBtnList.user_name" placeholder="请输入用户名称" />
          </el-form-item>
          <el-form-item label="账号ID">
            <el-input v-model="formBtnList.dpl_id" placeholder="请输入账号ID" />
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="formBtnList.phone" :prefix-icon="Search" placeholder="请输入用户名或电话或账号ID" />
          </el-form-item>
        </el-form>
      </template>
    </Table>

    <!-- 弹窗 -->
    <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
      :formData="formData" :ruleForm="ruleForm" :rules="rules" @beforeClose="beforeClose" @dialogSwitch="dialogSwitch"
      @submitForm="submitForm" />
    <!-- 详情弹窗 -->
    <!-- <userManagementDialog ref="dialogCom" :dialogVisible="dialogVisible2" :btnLoading="btnLoading2"
      :ruleForm="ruleForm2" :tableTitle="tableTitle2" :isStatus="isStatus"
      @beforeClose="beforeClose2" @submitForm="submitForm2">
    </userManagementDialog> -->
  </div>
</template>

<script setup lang='ts' name="Dashboard">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import DialogCom from '@/components/DialogCom.vue';
// import userManagementDialog from '@/views/userManagement/userManagementDialog.vue';   //用户封禁弹窗
import { Search } from '@element-plus/icons-vue'
import { userDel, userAdd, userEdit,getUser} from '@/api/admin/index.ts'
// 表格相关 开始
const loading = ref(false)
// 分页 数据总数
const total = ref(0)
// 表头数据
const columns = ref([
  { prop: 'user_id', label: '用户ID', width: 110 },
  { prop: 'dpl_id', label: '账号ID', width: 200 },
  { prop: 'user_name', label: '用户名', width: '' },
  { prop: 'add_time', label: '注册时间', width: 250, },
  { prop: 'phone', label: '电话', width: 200 },
  { prop: 'is_bind_wx', label: '是否绑定微信', width: 200,formatter: (row: any) => row.is_bind_wx == '1' ? '是' : '否'},    //缺字段
  // { prop: 'email', label: '邮件地址', width: '' },
  { prop: 'status', label: '用户状态', width: 120, formatter: (row: any) => row.status == '1' ? '正常' : '异常' },
  // { prop: 'avatar_url', label: '头像', width: 90, isImg: true, height: 20 },
  // 当是否激活为true时，显示"是"
  // { prop: 'is_active', label: '是否激活', width: 120, formatter: (row: any) => row.is_active ? '是' : '否' },
  // { prop: 'updated_at', label: '更新时间', width: 180 },
  // { prop: 'exp_time', label: '处罚过期时间', width: 200},
]);
// 表格数据
const paginatedData = ref([
  // { user_id: 'ID', user_name: '苏珊', email: 'singJumpRapBasketball@ikun.com', phone: '12345678901', is_active: true, created_at: '2023-10-05T14:48:00.000Z' },
  // { user_id: 'ID', user_name: '打球被笑两年半', email: 'kunkun@ikun.com', is_active: false, created_at: '2023-10-05T14:48:00.000Z', profile_picture_url: require('@/assets/image/giegie.jpg') },
]);
// 查询条件
const formBtnList = reactive({
  status: '',
  page_size: 10,
  page: 1,
  user_name:'',
  dpl_id:'',
  phone:''
})
const handleOnSelect = () => {
  handInquire()
}
let statusOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: '0',
    label: '异常',
  },
  {
    value: '1',
    label: '正常',
  },
])
// 封禁弹窗相关
// const dialogVisible2 = ref(false)
// const btnLoading2 = ref(false)
// const tableTitle2 = ref('');
// const isStatus = ref(-1)
// const beforeClose2 = () => {
//   dialogVisible2.value = false;
// }
// 弹窗 确认按钮 (ruleFormData: any)
// const submitForm2 = (ruleFormData:any) => {
//   dialogVisible2.value = false
//   // 处理封禁
// }
// 查询点击事件
// const handInquire = () => {
//   loading.value = true
//   user(formBtnList, 'cn').then((res: any) => {
//     if (res.code === 200) {
//       total.value = res.data.total
//       if (res.data.total === 0) {
//         ElMessage.error(`用户信息不存在`)
//         paginatedData.value = []
//         return
//       }
//       const processedData = res.data.users.map((item: Object) => {
//         return {
//           ...item,
//           judData: item.status  // 添加 judData 属性，并赋值为 status
//         };
//       });
//       paginatedData.value = processedData
//     } else {
//       paginatedData.value = []
//       ElMessage.error(`请求错误: ${res.msg}`)
//     }
//   }).finally(() => {
//     loading.value = false
//   })
// }
const handInquire = () => {
  loading.value = true
  getUser(formBtnList).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.total
      if (res.data.total === 0) {
        ElMessage.error(`用户信息不存在`)
        paginatedData.value = []
        return
      }
      const processedData = res.data.users.map((item: any) => {
        return {
          ...item,
          judData: item.status  // 添加 judData 属性，并赋值为 status
        };
      });
      paginatedData.value = processedData
    } else {
      paginatedData.value = []
      ElMessage.error(`请求错误: ${res.msg}`)
    }
  }).finally(() => {
    loading.value = false
  })
}
interface RuleForm {
  user_id: string
  dpl_id: string
  user_name: string
  phone: string
  email: string
  status: string
  avatar_url: string
}

// 表单数据
const ruleForm = reactive({})
// 封禁和详情弹窗数据
// const ruleForm2 = ref([{handle_type:'',limit_time:null,exp_time:'',handle_remark:''}])

// 重置表单方法
// const resetForm = (initialData?: Partial<RuleForm>) => {
//   Object.assign(ruleForm, {
//     user_id: '',
//     dpl_id: '',
//     user_name: '',
//     phone: '',
//     email: '',
//     status: '',
//     avatar_url: '',
//     ...(initialData || {}),
//   });
// };
// 表单控件数据
let formData = reactive([
  { type: 'input', label: '用户名', prop: 'user_name', span: 24, placeholder: '请输入' },
  { type: 'input', label: '手机号码', prop: 'phone', span: 24, placeholder: '请输入' },
  { type: 'input', label: '邮件', prop: 'email', span: 24, placeholder: '请输入' },
  // { type: 'select', label: '是否激活', prop: 'status', span: 24, placeholder: '请选择', options: numberOptions, },
])
// 新增
// const handAddAccount = () => {
//   resetForm();
//   formData = [
//     { type: 'input', label: '用户名', prop: 'user_name', span: 24, placeholder: '请输入' },
//     { type: 'input', label: '手机号码', prop: 'phone', span: 24, placeholder: '请输入' },
//     { type: 'input', label: '邮件', prop: 'email', span: 24, placeholder: '请输入' },
//   ]
//   tableTitle.value = '添加账户'
//   dialogVisible.value = true
// }
// 编辑
// const handEditAccount = (row: object, index: number) => {
//   resetForm(row);
//   formData = [
//     { type: 'input', label: '用户名', prop: 'user_name', span: 24, placeholder: '请输入' },
//   ]
//   tableTitle.value = '编辑'
//   dialogVisible.value = true
// }
// 重置
const handDerived = () => {
  // console.log('重置')
  formBtnList.status = ''
  formBtnList.phone=''
  formBtnList.user_name=''
  formBtnList.dpl_id=''
  // formBtnList.page_size= 10,
  // formBtnList.page= 1,
  paginatedData.value = []
  handInquire()
}
// 按钮组
const btnList = [
  { name: '查询', type: 'primary', click: handInquire, icon: '' },
  { name: '重置', type: 'success', click: handDerived, icon: '' },
]
// const footerBtnList = [
//   { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
// ]
// 删除
const del = (row: any) => {
  ElMessageBox.confirm(
    '是否删除?',
    '删除',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    userDel(row.user_id).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch(() => {
    }).finally(() => {
      handInquire()
    })
  }).catch(() => {

  })
}
// 处理弹窗 handle
// const handle = (row: any, index: number) => {
//   console.log(index);
//   // todo 获取详情？// getDetail(String(row.report_id))
//   // getRuleForm(row.report_id)
//   tableTitle2.value = '举报处理'
//   isStatus.value = 0
//   dialogVisible2.value = true
// }
// 详情弹窗
// const details = (row: any, index: number) => {
//   console.log(index);
//   // todo 获取详情 
//   // getDetail(row.report_id)
//   tableTitle2.value = '举报详情'
//   isStatus.value =1
//   dialogVisible2.value = true
// }
// 禁用
const updateStatus = (row: any,)=>{
  if(row.status == '1'){
    ElMessageBox.confirm(
      '确定要禁用该用户吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // type: 'warning',
      }
    ).then(() => {
      userEdit({user_id:row.user_id,status:'0'}).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: '成功',
            type: 'success',
          })
        }
      }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
      }).finally(() => {
        handInquire()
      })
    }).catch(() => {})
  }else if(row.status == '0' && localStorage.getItem('role_id')=='超级管理员'){
    ElMessageBox.confirm(
      '确定要解除禁用该用户吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // type: 'warning',
      }
    ).then(() => {
      userEdit({user_id:row.user_id,status:'1'}).then((res: any) => {
        if (res.code === 200) {
          ElMessage({
            message: '成功',
            type: 'success',
          })
        }
      }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
      }).finally(() => {
        handInquire()
      })
    }).catch(() => {})
  }else if(localStorage.getItem('role_id')!=='超级管理员'){
    ElMessage({
    message: '普通管理员不可解除用户的禁用状态',
    type: 'warning',
  })
  }
  
}
// 操作列按钮组
const btnListTable = ref([
  // { name: '编辑', type: 'success', click: handEditAccount },
  // { name: '封禁', type: 'warning', click: handle,judgment: true, isShow: ['1'],color:'#F77381' },
  // { name: '封禁详情', type: 'primary', click: details,judgment: true, isShow: ['0']},
  { name: '禁用', type: 'warning', click: updateStatus,judgment:true, isShow: ['1'],color:'#F77381' },
  { name: '解封', type: 'info',click: updateStatus, judgment: true, isShow: ['0'] },
  { name: '删除', type: 'danger', click: del },
])

// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
  // console.log('handlePageSize', pageSize);
  formBtnList.page_size = pageSize
  handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
  // console.log('handleCurrentPage', currentPage);
  formBtnList.page = currentPage
  handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)

// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
  user_id: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  user_name: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
  ],
  // email: [
  //   { required: true, message: '此项为必填项', trigger: 'blur' },
  // ],
  phone: [
    { required: true, message: '此项为必填项', trigger: 'blur' },
    { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    },
  ],
})
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any, tableTitle: string) => {
  if (tableTitle === '添加账户') {
    let para = {
      user_name: ruleFormData.user_name,
      phone: ruleFormData.phone,
      email: ruleFormData.email,
    }
    btnLoading.value = true
    userAdd(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
      } else {
        ElMessage.error(`请求错误: ${res.msg}`)
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      btnLoading.value = false
      handInquire()
    })
  } else if (tableTitle === '编辑') {
    let para = {
      user_id: ruleFormData.user_id,
      user_name: ruleFormData.user_name,
    }
    btnLoading.value = true
    userEdit(para).then((res: any) => {
      if (res.code === 200) {
        if (dialogCom.value) {
          dialogCom.value.cancelClick(); // 调用子组件方法
        }
        ElMessage({
          message: '成功',
          type: 'success',
        })
      }
    }).catch((error: any) => {
      ElMessage.error(`请求错误: ${error.msg}`)
    }).finally(() => {
      btnLoading.value = false
      handInquire()
    })
  }
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const beforeClose = () => {
  dialogVisible.value = false;
}
const dialogSwitch = (row: object) => {
  console.log('row: ', row);

}
onMounted(() => {
  handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
  .el-input {
    width: 265px;

  }

  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }

}
</style>